﻿#region License
// MIT License
//
// Copyright(c) 2019-2025 ZhangYu
// https://gitee.com/zhangyu800/litebyte
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
#region Intro
// Purpose: Scan source code and get tokens
// Author: ZhangYu
// CreateDate: 2019-10-18
// LastModifiedDate: 2025-02-06
#endregion
namespace LiteByte.Analyzers {

    using System.Collections.Generic;

    /// <summary>
    /// <para> 词法分析器 | Lexical analyzer </para>
    /// </summary>
    public class LexicalAnalyzer {

        #region Fields
        /// <summary> 空白Token </summary>
        private static readonly LexicalToken EmptyToken = new LexicalToken();
        /// <summary> 当前要分析的文本 </summary>
        private string text;
        /// <summary> 当前字符 </summary>
        private char c;
        /// <summary> 当前字符的序号 </summary>
        private int index;
        /// <summary> 当前字符所属行 </summary>
        private int row;
        /// <summary> 当前字符所属列 </summary>
        private int column;
        /// <summary> 临时数据 </summary>
        private TempToken temp;
        /// <summary> 词法分析后的Tokens </summary>
        private List<LexicalToken> tokens;

        /// <summary> 临时数据 </summary>
        private class TempToken {

            public TokenTag tag = TokenTag.None;
            public char c = '\x0';
            public int row = 0;
            public int column = 0;
            public int index = 0;
            public int length = 0;

        }
        #endregion

        #region API
        /// <summary> 词法分析(拆分成词法单元) | Lexical analyze(split and get lexical element) </summary>
        public List<LexicalToken> Analyze(string text) {
            if (string.IsNullOrEmpty(text)) return new List<LexicalToken>();
            row = 1;
            column = 0;
            this.text = text;
            temp = new TempToken();
            tokens = new List<LexicalToken>();

            // 扫描所有字符 | Scan all chars
            for (index = 0; index < text.Length; index++) {
                c = text[index];
                switch (c) {
                    case ' ' or '\t':
                        AddTempToken();
                        break;
                    case '\r' or '\0':
                        // 忽略这个符号 | Ignore this character
                        break;
                    case '\n':
                        // 换行符 | New line character
                        AddTempToken();
                        Newline();
                        break;
                    case ',':
                        AddCurrToken(TokenTag.Comma, ",");
                        break;
                    case ':':
                        AddCurrToken(TokenTag.Colon, ":");
                        break;
                    case ';':
                        AddCurrToken(TokenTag.Semicolon, ";");
                        break;
                    case '%':
                        AddCurrToken(TokenTag.Mod, "%");
                        break;
                    case '=':
                        AddCurrToken(TokenTag.Equal, "=");
                        break;
                    case '?':
                        AddCurrToken(TokenTag.Question, "?");
                        break;
                    case '&':
                        AddCurrToken(TokenTag.BitwiseAnd, "&");
                        break;
                    case '|':
                        AddCurrToken(TokenTag.BitwiseOr, "|");
                        break;
                    case '!':
                        AddCurrToken(TokenTag.LogicNot, "!");
                        break;
                    case '~':
                        AddCurrToken(TokenTag.BitReverse, "~");
                        break;
                    case '^':
                        AddCurrToken(TokenTag.BitwiseXOR, "^");
                        break;
                    case '<':
                        AddCurrToken(TokenTag.LAngle, "<");
                        break;
                    case '>':
                        AddCurrToken(TokenTag.RAngle, ">");
                        break;
                    case '(':
                        AddCurrToken(TokenTag.LParen, "(");
                        break;
                    case ')':
                        AddCurrToken(TokenTag.RParen, ")");
                        break;
                    case '{':
                        AddCurrToken(TokenTag.LBrace, "{");
                        break;
                    case '}':
                        AddCurrToken(TokenTag.RBrace, "}");
                        break;
                    case '[':
                        AddCurrToken(TokenTag.LSquare, "[");
                        break;
                    case ']':
                        AddCurrToken(TokenTag.RSquare, "]");
                        break;
                    case '+':
                        AddCurrToken(TokenTag.Plus, "+");
                        break;
                    case '-':
                        AddCurrToken(TokenTag.Minus, "-");
                        break;
                    case '*':
                        AddCurrToken(TokenTag.Multiply, "*");
                        break;
                    case '/':
                        switch (NextChar) {
                            case '/':
                                // 单行注释开始 | Single-line comments start
                                index += 1;
                                // 查找单行注释结束 '\n' | Find single-line comments end '\n'
                                while (index + 1 < text.Length) {
                                    index++;
                                    c = text[index];
                                    if (c == '\n') {
                                        Newline();
                                        break;
                                    }
                                }
                                break;
                            case '*':
                                // 多行注释开始 | Multi-line comments start
                                index += 1;
                                // 查找多行注释结束 "*/" | Find multi-line comments end "*/"
                                while (index + 1 < text.Length) {
                                    index++;
                                    c = text[index];
                                    if (c == '\n') {
                                        Newline();
                                    } else if (c == '*' && NextChar == '/') {
                                        index += 1;
                                        break;
                                    }
                                }
                                break;
                            default:
                                AddCurrToken(TokenTag.Divide, "/");
                                break;
                        }
                        break;
                    default:
                        // 其他字母 | Other characters
                        if (temp.length == 0) {
                            // 新的片段开始 | New segment start
                            UpdateTemp(TokenTag.Segment, c, row, column, index, 1);
                        } else {
                            temp.length += 1;
                        }
                        break;
                }
                column += 1;
            }
            AddTempToken();
            var result = tokens;
            ClearData();
            return result;
        }
        #endregion

        #region Tool
        private void Newline() {
            row += 1;
            column = 0;
        }

        private void ClearData() {
            text = "";
            c = '\0';
            index = 0;
            row = 1;
            column = 0;
            temp = null;
            tokens = null;
        }

        private void AddTempToken() {
            if (temp.length < 1) return;
            AddToken(temp.tag, text.Substring(temp.index, temp.length), temp.row, temp.column);
            ClearTemp();
        }

        private void AddCurrToken(TokenTag tag, string value) {
            AddTempToken();
            AddToken(tag, value, row, column);
        }

        private void ClearTemp() {
            UpdateTemp(TokenTag.None, '\x0', 0, 0, 0, 0);
        }

        private void UpdateTemp(TokenTag tag, char chr, int row, int column, int index, int length) {
            temp.tag = tag;
            temp.c = chr;
            temp.row = row;
            temp.column = column;
            temp.index = index;
            temp.length = length;
        }

        /// <summary> 添加一个词法单元信息到列表 | Add a token to list </summary>
        private void AddToken(TokenTag tag, string value, int row, int column) {
            if (IsSpace(value)) return;
            switch (tag) {
                case TokenTag.Segment:
                    if (IsIdentifier(value)) {
                        tokens.Add(new LexicalToken(IsAccessModifier(value) ? TokenTag.AccessModifier : TokenTag.Identifier, row, column, value));
                    } else {
                        tokens.Add(new LexicalToken(tag, row, column, value));
                    }
                    break;
                default:
                    tokens.Add(new LexicalToken(tag, row, column, value));
                    break;
            }
        }

        private char NextChar {
            get { return index + 1 < text.Length ? text[index + 1] : '\0'; }
        }
        #endregion

        #region String Match
        private static bool IsSpace(string str) {
            if (string.IsNullOrEmpty(str)) return true;
            switch (str) {
                case "\0" or " " or "\t" or "\r" or "\n": return true;
                default: return false;
            }
        }

        /// <summary> 是否是数字</summary>
        private static bool IsDigit(char c) {
            if (c >= '0' && c <= '9') return true;
            return false;
        }

        /// <summary> 是否是访问修饰符 | Check if is a access modifier </summary>
        private static bool IsAccessModifier(string str) {
            if (string.IsNullOrEmpty(str)) return false;
            switch (str) {
                case "public" or "private" or "protected" or "internal": return true;
                default: return false;
            }
        }

        /// <summary> 是否是标识符 | Check if is a identifier </summary>
        private static bool IsIdentifier(string str) {
            if (string.IsNullOrEmpty(str)) return false;
            return !IsDigit(str[0]);
        }
        #endregion

    }

}